﻿#include "controlled.h"

#include  "device.h"
#include "wordopledcontroller.h"

ControlLED::ControlLED(QObject *parent)
    : Operation{parent}
    , m_pDescription((Description*)parent)
    , m_pLedController(new WordopLedController(this))
{}

int ControlLED::nChannel() const
{
    return m_nChannel;
}

void ControlLED::setNChannel(int newNChannel)
{
    m_nChannel = newNChannel;
}

int ControlLED::nValue() const
{
    return m_nValue;
}

void ControlLED::setNValue(int newNValue)
{
    m_nValue = newNValue;
}

void ControlLED::run(){
    qDebug() << "ControlLED is Running!";
    qDebug() << QString("channel = %1,value = %2").arg(m_nChannel).arg(m_nValue);

    Device* pDevice = m_pDescription->FindDeviceById(m_strDeviceID);
    QString message = QString("ControlLED : channel = %1 and value = %2.").arg(m_nChannel).arg(m_nValue);
    pDevice->writeData(m_pLedController->control(m_nChannel,m_nValue));
}

void ControlLED::writeXML(QXmlStreamWriter& writer){
    // 写入当前操作的信息
    writer.writeStartElement("ControlLED");
    writer.writeAttribute("device", m_strDeviceID);
    writer.writeTextElement("channel", QString::number(m_nChannel));
    writer.writeTextElement("value", QString::number(m_nValue));
    writer.writeEndElement();  // 结束当前操作的元素
}

void ControlLED::readFromXML(QXmlStreamReader& reader){
    QXmlStreamAttributes attributes = reader.attributes();
    if(attributes.hasAttribute("device")) {
        m_strDeviceID = attributes.value("device").toString();
    }

    QXmlStreamReader::TokenType token = reader.readNext();
    while (!(reader.tokenType() == QXmlStreamReader::EndElement &&
             reader.name() == QStringLiteral("ControlLED"))) {

        if (reader.name() == QStringLiteral("channel")) {
            m_nChannel = reader.readElementText().toInt();
        }else if (reader.name() == QStringLiteral("value")) {
            m_nValue = reader.readElementText().toInt();
        }

        reader.readNext();
    }
}
